package com.tiancheng.trade.settlement.configuration;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class JsonLocalDateTimeFormatter {
    private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static LocalDateTimeSerializer buildSerializer() {
        return new LocalDateTimeSerializer();
    }

    public static LocalDateTimeDeserializer buildDeserializer() {
        return new LocalDateTimeDeserializer();
    }

    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            String string = FORMAT.format(value);
            gen.writeString(string);
        }
    }

    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String dateStr = jp.getText();

            if (StringUtils.isBlank(dateStr)) {
                return null;
            }
            LocalDateTime data = null;
            try {
                data = LocalDateTime.parse(dateStr, FORMAT);
            } catch (Exception e) {
                data = LocalDateTime.parse(dateStr, JsonLocalDateFormatter.FORMAT);
            }
            return data;
        }
    }

}